<template>
  <div>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="600px" @close="cancel">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="ruleForm.userName" maxlength="64" />
        </el-form-item>
        <el-form-item label="姓名" prop="userRealName">
          <el-input v-model="ruleForm.userRealName" maxlength="64" />
        </el-form-item>
        <div v-if="!editPassword" class="psw-btn"><el-button size="mini" @click="editPassword = true">修改密码</el-button></div>
        <div v-else-if="editPassword">
          <el-form-item label="密码" prop="userPassword">
            <el-input v-model="ruleForm.userPassword" type="password" autocomplete="off" maxlength="64" />
          </el-form-item>
          <el-form-item v-if="title === '新建用户'" label="确认密码" prop="userPasswordCheck">
            <el-input v-model="ruleForm.userPasswordCheck" type="password" autocomplete="off" maxlength="64" />
          </el-form-item>
        </div>
        <el-form-item label="联系方式" prop="userPhone">
          <el-input v-model="ruleForm.userPhone" maxlength="64" />
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="ruleForm.roleId" filterable multiple placeholder="请选择角色" style="width: 100%;">
            <el-option v-for="item in roles" :key="item.roleId" :label="item.roleName" :value="item.roleId" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门" prop="departmentName">
          <el-select ref="departmentName" v-model="departmentName" filterable placeholder="请选择部门">
            <el-option class="select-tree" :value="dataOrgTree">
              <div class="select-tree-box">
                <el-scrollbar style="height: 100%">
                  <el-tree ref="tree" class="orgTree elc-tree" :data="dataOrgTree" default-expand-all node-key="id" :expand-on-click-node="false"
                    highlight-current :props="defaultProps" @node-click="(data) => changeTree(data)" />
                </el-scrollbar>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :loading="loading" type="primary" @click="submitForm('ruleForm')">
            <span v-if="!loading">确认</span>
            <span v-else>创建中...</span>
          </el-button>
          <el-button @click="cancel('ruleForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { createUser, updateUser } from '@/api/user'
import AES from '@/components/AES/AES'
export default {
  props: ['roles', 'dataOrgTree'],
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.ruleForm.userPassword) {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }
    var validatePass3 = (rule, value, callback) => {
      if (this.departmentName === '') {
        callback(new Error('请选择部门'))
      }
    }
    return {
      editPassword: true,
      defaultProps: {
        children: 'childrenDept',
        label: 'deptName'
      },
      title: '',
      loading: false,
      dialogVisible: false,
      departmentId: '',
      departmentName: '',
      ruleForm: {
        userName: '',
        userRealName: '',
        userPassword: '',
        userPasswordCheck: '',
        userPhone: '',
        roleId: ''
      },
      id: '',
      rules: {
        userName: [
          { required: true, message: '请输入用户名称', trigger: 'blur' }
        ],
        userRealName: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        userPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        userPasswordCheck: [
          { required: true, validator: validatePass2, trigger: 'blur' }
        ],
        userPhone: [
          { required: true, message: '请输入联系方式', trigger: 'blur' }
        ],
        roleId: [
          { required: true, message: '请选择角色', trigger: 'blur' }
        ],
        departmentName: [
          { required: true, validator: validatePass3, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    changeTree(data) {
      this.departmentName = data.deptName
      this.departmentId = data.id
      this.$refs['departmentName'].blur()
    },
    show(obj) {
      this.departmentId = '',
        this.departmentName = '',
        this.ruleForm = {
          userName: '',
          userRealName: '',
          userPassword: '',
          userPasswordCheck: '',
          userPhone: '',
          roleId: ''
        },
        this.editPassword = true
      this.title = obj.title
      if (this.title === '修改用户') {
        this.editPassword = false
        this.rules.userPassword[0].required = false
        const userData = obj.data
        this.ruleForm = {
          userName: userData.user.userName,
          userRealName: userData.user.userRealName,
          userPassword: '',
          userPasswordCheck: '',
          userPhone: userData.user.userPhone,
          roleId: userData.roleIds
        },
          this.id = userData.user.id
        this.departmentName = userData.user.deptName
        this.departmentId = userData.user.deptId
      }

      this.roles.forEach(item => {
        if (item.roleName === this.ruleForm.roleName) {
          this.ruleForm.roleId = item.id
        }
      })

      console.log(obj)
      this.dialogVisible = true
    },
    submitForm() {
      if (this.title === '新建用户') {
        if (this.ruleForm.userName !== '' && this.ruleForm.userName !== undefined && this.ruleForm.userRealName !== '' && this.ruleForm.userRealName !== undefined && this.ruleForm.userPassword !== '' && this.ruleForm.userPassword !== undefined && this.ruleForm.userPhone !== '' && this.ruleForm.userPhone !== undefined && this.ruleForm.roleId !== '' && this.ruleForm.roleId.length !== 0 && this.departmentName !== '') {
          this.$refs.ruleForm.validate(() => { })
          const params = {
            userName: this.ruleForm.userName,
            userRealName: this.ruleForm.userRealName,
            userPassword: AES.encrypt(JSON.stringify(this.ruleForm.userPassword)),
            userPhone: this.ruleForm.userPhone,
            roleIds: this.ruleForm.roleId,
            deptId: this.departmentId
          }
          createUser(params).then(res => {
            if (res.code === 200) {
              this.$message({
                showClose: true,
                message: '新增用户成功',
                type: 'success'
              })
              this.departmentId = ''
              this.departmentName = ''
              this.$refs.ruleForm.resetFields()
              this.dialogVisible = false
              this.$emit('init')
            } else {
              this.$message({
                showClose: true,
                message: res.message,
                type: 'warning'
              })
            }
          }).catch(err => {
            console.log(err)
          })
        } else {
          this.$refs.ruleForm.validate(() => {

          })
        }
      } else if (this.title === '修改用户') {
        if (this.ruleForm.userName !== '' && this.ruleForm.userName !== undefined && this.ruleForm.userRealName !== '' && this.ruleForm.userRealName !== undefined && this.ruleForm.userPhone !== '' && this.ruleForm.userPhone !== undefined && this.ruleForm.roleId !== '' && this.ruleForm.roleId.length !== 0 && this.departmentName !== '') {
          this.$refs.ruleForm.validate(() => { })
          const params = {
            id: this.id,
            userName: this.ruleForm.userName,
            userRealName: this.ruleForm.userRealName,
            // userPassword: AES.encrypt(JSON.stringify(this.ruleForm.userPassword)),
            userPhone: this.ruleForm.userPhone,
            roleIds: this.ruleForm.roleId,
            deptId: this.departmentId
          }
          if (this.ruleForm.userPassword !== '') {
            params.userPassword = AES.encrypt(JSON.stringify(this.ruleForm.userPassword))
          }
          updateUser(params).then(res => {
            if (res.code === 200) {
              this.$message({
                showClose: true,
                message: '修改用户成功',
                type: 'success'
              })
              this.departmentId = ''
              this.departmentName = ''
              this.$refs.ruleForm.resetFields()
              this.dialogVisible = false
              this.$emit('init')
            } else {
              this.$message({
                showClose: true,
                message: res.message,
                type: 'warning'
              })
            }
          }).catch(err => {
            console.log(err)
          })
        } else {
          this.$refs.ruleForm.validate(() => {
          })
        }
      }
    },
    cancel() {
      this.departmentId = ''
      this.departmentName = ''
      this.$refs.ruleForm.resetFields()
      this.dialogVisible = false
    }
  }
}
</script>
<style lang="less" scoped>
  .psw-btn {
    margin-left: 100px;
    margin-bottom: 20px;
  }
</style>
